﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;
using System.Runtime.Serialization.Formatters.Binary;
using System.Net;
using System.IO;
using System.Threading;
using System.Globalization;


namespace MulticastTV
{
    public partial class CheckForNewChannels : Form
    {
        static CookieContainer cookieContainer = new CookieContainer();
        static string cookieFile = Globals.UserAppPath + @"\..\cookies.bin";

        Thread threadAvailable;
        Thread threadNewChannels;

        volatile bool abortThread1 = false;
        volatile bool abortThread2 = false;

        DataTable downloadDatatable = new DataTable();
        DataTable RenameDelete = null;
        Form1 parent;

        public CheckForNewChannels(Form1 pr)
        {
            parent = pr;

            InitializeComponent();

            if (Thread.CurrentThread.CurrentUICulture.IetfLanguageTag == "sl-SI")
            {
                MLmessages.Culture = new CultureInfo("sl-SI");
            }

            loadCookiesFromFile();

            DataColumn column1 = new DataColumn();

            column1.DataType = typeof(int);
            column1.ColumnName = "Channel";
            column1.DefaultValue = 0;
            column1.ReadOnly = false;
            column1.Unique = false;
            downloadDatatable.Columns.Add(column1);

            DataColumn column2 = new DataColumn();

            column2.DataType = typeof(string);
            column2.ColumnName = "Name";
            column2.DefaultValue = "";
            column2.ReadOnly = false;
            column2.Unique = false;
            downloadDatatable.Columns.Add(column2);

            DataColumn column3 = new DataColumn();

            column3.DataType = typeof(string);
            column3.ColumnName = "Locked";
            column3.DefaultValue = "";
            column3.ReadOnly = false;
            column3.Unique = false;
            downloadDatatable.Columns.Add(column3);

            DataColumn column4 = new DataColumn();

            column4.DataType = typeof(string);
            column4.ColumnName = "Group";
            column4.DefaultValue = "";
            column4.ReadOnly = false;
            column4.Unique = false;
            downloadDatatable.Columns.Add(column4);

            DataColumn column5 = new DataColumn();

            column5.DataType = typeof(string);
            column5.ColumnName = "Language";
            column5.DefaultValue = "";
            column5.ReadOnly = false;
            column5.Unique = false;
            downloadDatatable.Columns.Add(column5);

            DataColumn column6 = new DataColumn();

            column6.DataType = typeof(string);
            column6.ColumnName = "Ip";
            column6.DefaultValue = "";
            column6.ReadOnly = false;
            column6.Unique = false;
            downloadDatatable.Columns.Add(column6);

            bindingSource1.DataSource = downloadDatatable;
            dataGridView1.Columns[1].DataPropertyName = "Channel";
            dataGridView1.Columns[1].Name = "Channel";
            dataGridView1.Columns[2].DataPropertyName = "Name";
            dataGridView1.Columns[2].Name = "Name";
            dataGridView1.Columns[3].DataPropertyName = "Locked";
            dataGridView1.Columns[3].Name = "Locked";
            dataGridView1.Columns[4].DataPropertyName = "Group";
            dataGridView1.Columns[4].Name = "Group";
            dataGridView1.Columns[5].DataPropertyName = "Language";
            dataGridView1.Columns[5].Name = "Language";
            dataGridView1.Columns[6].DataPropertyName = "Ip";
            dataGridView1.Columns[6].Name = "Ip";
            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = bindingSource1;

            listView1.HideSelection = false;

            toolTip1.ShowAlways = true;
        }

        public delegate void delegateParentThread();
        public delegate void delegateParentThreadListItem(ListViewItem li);
        public delegate void delegateEnableButtons(Button button);
        public delegate void delegateUpdateLabels(string text);

        string xmlUrl = "";
        string playlistLink = "";
        static string format = "xls";
        string downloadFile = Globals.UserAppPath + @"\..\channels-online-temp.temp";
        bool clearCookies = false;

        private void CheckForNewChannels_Load(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.CheckForNewDelete)
                checkBox1.CheckState = CheckState.Checked;
            else
                checkBox1.CheckState = CheckState.Unchecked;

            if (Properties.Settings.Default.CheckForNewRename)
                checkBox2.CheckState = CheckState.Checked;
            else
                checkBox2.CheckState = CheckState.Unchecked;

            button2.Enabled = false;
            button3.Enabled = false;
            label3.ForeColor = Color.Black;
            textBox1.Text = Properties.Settings.Default.CheckForNewURI;
            if (textBox1.Text != string.Empty)
                refresh();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            refresh();
        }

        private void refresh()
        {
            button1.Enabled = false;
            button2.Enabled = false;
            button3.Enabled = false;

            if (listView1.Items.Count > 0)
                listView1.Items.Clear();

            xmlUrl = textBox1.Text;
            threadAvailable = new Thread(new ThreadStart(startThread));
            threadAvailable.IsBackground = true;
            threadAvailable.Start();
        }

        private void startThread()
        {
            getAvailableChannelLists(xmlUrl);
        }

        /// <summary>
        /// Load xml from remote location.
        /// </summary>
        private void getAvailableChannelLists(string url)
        {
            if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
            {
                if (!abortThread1)
                    button1.Invoke(new delegateEnableButtons(enableButtons), button1);
                return;
            }

            // Get xml stream
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.CookieContainer = cookieContainer;
            req.Timeout = 8000;

            WebResponse resp;
            try
            {
                if (!abortThread1)
                    label3.Invoke(new delegateUpdateLabels(updateLabel), MLmessages.InternetConnecting);
                resp = req.GetResponse();
            }
            catch (System.Net.WebException e)
            {
                if (!abortThread1)
                    label3.Invoke(new delegateUpdateLabels(updateLabel), e.Status.ToString());
                if (!abortThread1)
                    button1.Invoke(new delegateEnableButtons(enableButtons), button1);
                return;
            }

            if (!abortThread1)
                label3.Invoke(new delegateUpdateLabels(updateLabel), MLmessages.FileReading);

            Stream data;
            try
            {
                data = resp.GetResponseStream();
            }
            catch (System.Net.WebException e)
            {
                if (resp != null)
                    resp.Close();
                if (!abortThread1)
                    label3.Invoke(new delegateUpdateLabels(updateLabel), e.Message);
                return;
            }

            XPathDocument xpth = new XPathDocument(data);
            data.Close();
            resp.Close();
            XPathNavigator xptnv = xpth.CreateNavigator();

            XPathExpression expr;
            expr = xptnv.Compile("/channels/provider/title | /channels/provider/link");
            XPathNodeIterator iterator = xptnv.Select(expr);

            if (!abortThread1)
                label3.Invoke(new delegateUpdateLabels(updateLabel), MLmessages.FileLoaded);
            if (!abortThread1)
                listView1.Invoke(new delegateParentThread(listView1.BeginUpdate));
            try
            {
                while (iterator.MoveNext())
                {
                    XPathNavigator nav2 = iterator.Current.Clone();
                    ListViewItem li = new ListViewItem();
                    li.Text = nav2.InnerXml;
                    iterator.MoveNext();
                    XPathNavigator nav3 = iterator.Current.Clone();
                    li.Tag = nav3.InnerXml;
                    if (!abortThread1)
                        listView1.Invoke(new delegateParentThreadListItem(updateListView), li);
                }
            }
            catch
            {
                if (!abortThread1)
                    listView1.Invoke(new delegateParentThread(listView1.EndUpdate));
            }
            if (!abortThread1)
            {
                listView1.Invoke(new delegateParentThread(listView1.EndUpdate));
                listView1.Invoke(new delegateParentThread(selectItem));
                button1.Invoke(new delegateEnableButtons(enableButtons), button1);
            }
        }

        private void NewChannels()
        {
            if (listView1.Items.Count > 0 && listView1.SelectedItems.Count > 0)
            {
                playlistLink = listView1.SelectedItems[0].Tag.ToString();
                if (downloadDatatable != null)
                    downloadDatatable.Clear();
                button3.Enabled = false;

                threadNewChannels = new Thread(new ThreadStart(startThread2));
                threadNewChannels.IsBackground = true;
                threadNewChannels.Start();
            }
        }

        private void startThread2()
        {
            showNewChannels(playlistLink);
        }

        /// <summary>
        /// Download excell playlist from remote loacation and check for new channels
        /// against static channel table primary key - IP.
        /// </summary>
        private void showNewChannels(string xlsLink)
        {
            xlsLink = UnescapeXml(xlsLink);
            string userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; sl; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729)";
            string Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            string AcceptLanguage = "sl,en-gb;q=0.7,en;q=0.3";
            // string AcceptEncoding = "gzip,deflate";
            string AcceptCharSet = "ISO-8859-2,utf-8;q=0.7,*;q=0.7";

            HttpWebRequest req;
            req = (HttpWebRequest)WebRequest.Create(xlsLink);
            req.Timeout = 8000;
            req.CookieContainer = cookieContainer;
            req.Credentials = CredentialCache.DefaultCredentials;
            req.AllowAutoRedirect = false;
            req.UserAgent = userAgent;
            req.Accept = Accept;
            //req.Referer = referer;
            req.KeepAlive = true;
            req.Headers.Add(HttpRequestHeader.AcceptLanguage, AcceptLanguage);
            //req.Headers.Add(HttpRequestHeader.AcceptEncoding, AcceptEncoding);
            req.Headers.Add(HttpRequestHeader.AcceptCharset, AcceptCharSet);

            if (!abortThread2)
                label3.Invoke(new delegateUpdateLabels(updateLabel), MLmessages.InternetConnecting);
            HttpWebResponse resp;
            try
            {
                resp = (HttpWebResponse)req.GetResponse();
            }
            catch
            {
                if (!abortThread2)
                    label3.Invoke(new delegateUpdateLabels(updateLabel), MLmessages.InternetTimeOut);
                if (!abortThread2)
                    button1.Invoke(new delegateEnableButtons(enableButtons), button1);
                return;
            }

            if (!abortThread2)
                label3.Invoke(new delegateUpdateLabels(updateLabel), MLmessages.InternetDownloading);

            // manually handle redirects
            for (int i = 0; i < 20; i++)
            {
                if (resp.StatusCode == HttpStatusCode.Redirect || resp.StatusCode == HttpStatusCode.Found || resp.StatusCode == HttpStatusCode.Moved || resp.StatusCode == HttpStatusCode.TemporaryRedirect)
                {
                    Uri uri = new Uri(resp.Headers["Location"].ToString());

                    // Manually add cookies
                    manuallyAddCookies(resp, uri);

                    resp.Close();
                    resp = null;
                    req = (HttpWebRequest)WebRequest.Create(uri.AbsoluteUri);
                    req.Timeout = 8000;
                    req.AllowAutoRedirect = false;
                    req.CookieContainer = cookieContainer;
                    req.UserAgent = userAgent;
                    req.Accept = Accept;
                    req.KeepAlive = true;
                    req.Headers.Add(HttpRequestHeader.AcceptLanguage, AcceptLanguage);
                    //req.Headers.Add(HttpRequestHeader.AcceptEncoding, AcceptEncoding);
                    req.Headers.Add(HttpRequestHeader.AcceptCharset, AcceptCharSet);

                    try
                    {
                        if (!abortThread2)
                            label3.Invoke(new delegateUpdateLabels(updateLabel), MLmessages.InternetDownloading);
                        resp = (HttpWebResponse)req.GetResponse();
                    }
                    catch
                    {
                        if (!abortThread2)
                            label3.Invoke(new delegateUpdateLabels(updateLabel), MLmessages.InternetTimeOut);
                        return;
                    }
                }
                else
                {
                    break;
                }
            }

            Stream data = null; ;
            try
            {
                // Check for excel mime type
                if (resp.ContentType.Contains("excel") || (resp.ResponseUri.LocalPath != null && resp.ResponseUri.LocalPath.EndsWith(".xls")))
                {
                    format = "xls";
                    downloadFile = Path.ChangeExtension(downloadFile, "." + format);
                    data = resp.GetResponseStream();
                }
                // csv
                else if (resp.ContentType.Contains("plain") || (resp.ResponseUri.LocalPath != null && resp.ResponseUri.LocalPath.EndsWith(".csv")))
                {
                    format = "csv";
                    downloadFile = Path.ChangeExtension(downloadFile, "." + format);
                    data = resp.GetResponseStream();
                }
                else
                {
                    if (resp != null)
                    {
                        data = resp.GetResponseStream();
                        resp.Close();
                        if (data != null)
                            data.Close();
                        if (!abortThread2)
                            label3.Invoke(new delegateUpdateLabels(updateLabel), MLmessages.FileErorrExcell1);
                    }
                    return;
                }
            }
            catch (WebException e)
            {
                if (resp != null)
                    resp.Close();
                if (!abortThread2)
                    label3.Invoke(new delegateUpdateLabels(updateLabel), e.Message);
                return;
            }

            // Download in commonapp folder and then use ImpoertFromExcell class
            FileStream fs;
            try
            {
                fs = new FileStream(downloadFile, FileMode.Create);

                byte[] read = new byte[256];
                int recv = data.Read(read, 0, read.Length);

                while (recv > 0)
                {
                    fs.Write(read, 0, recv);
                    recv = data.Read(read, 0, read.Length);
                }
            }
            catch
            {
                if (data != null)
                    data.Close();
                if (resp != null)
                    resp.Close();
                return;
            }
            //Close everything
            if (!abortThread2)
                label3.Invoke(new delegateUpdateLabels(updateLabel), MLmessages.InternetDownloadSuccess);
            fs.Close();
            data.Close();
            resp.Close();

            if (!abortThread2)
                button3.Invoke(new delegateEnableButtons(enableButtons), button3);
            //this.Invoke(new delegateParentThread(checkForNewChannels));
            checkForNewChannels();

        }

        private void manuallyAddCookies(HttpWebResponse resp, Uri uri)
        {
            CookieCollection storedCookies = cookieContainer.GetCookies(uri);
            if (resp != null && resp.Cookies != null && storedCookies != null)
            {
                foreach (Cookie ck in resp.Cookies)
                {
                    foreach (Cookie cookie in storedCookies)
                    {
                        if (ck != cookie)
                            cookieContainer.Add(resp.Cookies);
                    }
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            label3.ForeColor = Color.Black;
            NewChannels();
        }

        private void checkForNewChannels()
        {
            if (!abortThread2)
                parent.Invoke(new delegateParentThread(addDataToDatatable));
        }

        private void addDataToDatatable()
        {
            // Form Thread
            if (File.Exists(downloadFile))
            {
                ImportFromExcel ifx = new ImportFromExcel(downloadFile);
                DataTable downloadDatatableTemp = downloadDatatable.Clone();

                if (format == "xls")
                    downloadDatatableTemp = ifx.ConvertToDatatable(null, false);
                if (format == "csv")
                {
                    downloadDatatableTemp = ifx.fromCsv(downloadFile, downloadDatatableTemp);
                }
                if (downloadDatatableTemp != null)
                {
                    downloadDatatable.BeginLoadData();
                    foreach (DataRow drTemp in downloadDatatableTemp.Rows)
                    {
                        string ip = drTemp["Ip"].ToString();
                        DataRow origRow = ChannelTable.menu.Tables["Menu"].Rows.Find(ip);
                        if (origRow == null)
                        {
                            downloadDatatable.ImportRow(drTemp);
                        }
                    }

                    downloadDatatable.EndLoadData();

                    // Update Gui with status
                    if (downloadDatatable.Rows.Count <= 1)
                    {
                        if (downloadDatatable.Rows.Count == 1)
                        {
                            if (downloadDatatable.Rows[0]["Name"].ToString() == "")
                            {
                                label3.Text = MLmessages.ChannelsNoNew;
                                label3.ForeColor = Color.Blue;
                                return;
                            }
                            else
                                return;
                        }

                        label3.Text = MLmessages.ChannelsNoNew;
                        label3.ForeColor = Color.Blue;
                    }
                    RenameDelete = downloadDatatableTemp;
                    deleteAndRename(downloadDatatableTemp, false);
                }
                else
                {
                    downloadDatatable = null;
                }
            }
        }

        private void refreshGrid()
        {
            dataGridView1.Refresh();
        }

        public string UnescapeXml(string s)
        {
            string unxml = s;
            if (!string.IsNullOrEmpty(unxml))
            {
                // replace entities with literal values
                unxml = unxml.Replace("&apos;", "'");
                unxml = unxml.Replace("&quot;", "\"");
                unxml = unxml.Replace("&gt;", "&gt;");
                unxml = unxml.Replace("&lt;", "&lt;");
                unxml = unxml.Replace("&amp;", "&");
            }
            return unxml;
        }

        private void saveCookiesToFile()
        {
            if (!clearCookies)
            {
                FileStream fs = new FileStream(cookieFile, FileMode.Create);
                try
                {
                    BinaryFormatter formatter = new BinaryFormatter();

                    formatter.Serialize(fs, cookieContainer);
                    fs.Close();
                }
                catch
                {
                    fs.Close();

                }
            }
        }

        private void loadCookiesFromFile()
        {
            if (File.Exists(cookieFile))
            {
                FileStream fs = new FileStream(cookieFile, FileMode.Open);
                try
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    cookieContainer = (CookieContainer)formatter.Deserialize(fs);
                    fs.Close();
                }
                catch
                {
                    fs.Close();
                }
            }
            else
            {
                cookieContainer = new CookieContainer();
            }
        }

        private void updateListView(ListViewItem li)
        {
            listView1.Items.Add(li);
        }

        private void updateLabel(string text)
        {
            label3.Text = text;
        }

        private void enableButtons(Button button)
        {
            button.Enabled = true;
        }

        private void selectItem(ListViewItem li)
        {
            li.Selected = true;
        }

        private void selectFirstItem()
        {
            listView1.Items[0].Selected = true;
        }

        private void selectItem()
        {
            if (listView1.Items.Count > 0)
            {
                enableButtons(button2);

                // select first item or find last item saved in preferences
                foreach (ListViewItem li in listView1.Items)
                {
                    if (li.Text == Properties.Settings.Default.ChecForNewLastPlaylist)
                    {
                        selectItem(li);
                        break;
                    }
                }
                if (listView1.SelectedItems.Count == 0)
                    selectFirstItem();
            }
        }

        private void CheckForNewChannels_FormClosing(object sender, FormClosingEventArgs e)
        {
            // terminate threads
            if (threadAvailable != null && threadAvailable.IsAlive)
            {
                abortThread1 = true;
                threadAvailable.Join(1000);
                threadAvailable.Abort();
            }

            if (threadNewChannels != null && threadNewChannels.IsAlive)
            {
                abortThread2 = true;
                threadNewChannels.Join(1000);
                threadNewChannels.Abort();
            }

            if (Uri.IsWellFormedUriString(textBox1.Text, UriKind.Absolute))
                Properties.Settings.Default.CheckForNewURI = textBox1.Text;

            if (listView1.Items.Count > 0 && listView1.SelectedItems.Count > 0)
            {
                Properties.Settings.Default.ChecForNewLastPlaylist = listView1.SelectedItems[0].Text;
            }

            if (checkBox1.CheckState == CheckState.Checked)
                Properties.Settings.Default.CheckForNewDelete = true;
            else
                Properties.Settings.Default.CheckForNewDelete = false;

            if (checkBox2.CheckState == CheckState.Checked)
                Properties.Settings.Default.CheckForNewRename = true;
            else
                Properties.Settings.Default.CheckForNewRename = false;

            Properties.Settings.Default.Save();
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dgw in dataGridView1.Rows)
            {
                DataGridViewCheckBoxCell dgwref = (DataGridViewCheckBoxCell)dgw.Cells[0];
                dgwref.Value = dgwref.TrueValue;
            }
        }

        private void deselectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow dgw in dataGridView1.Rows)
            {
                DataGridViewCheckBoxCell dgwref = (DataGridViewCheckBoxCell)dgw.Cells[0];
                dgwref.Value = dgwref.FalseValue;
            }
        }

        private void CheckForNewChannels_FormClosed(object sender, FormClosedEventArgs e)
        {
            saveCookiesToFile();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            clearCookies = true;
            cookieContainer = null;
            cookieContainer = new CookieContainer();
            if (File.Exists(cookieFile))
            {
                try
                {
                    File.Delete(cookieFile);
                }
                catch (Exception ex)
                {
                    label3.Text = ex.Message;
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            updateMainChannelTable();
            if (!abortThread2)
                parent.Invoke(new delegateParentThread(parent.channelManagementReconfiguration));
            this.Close();
        }

        private void updateMainChannelTable()
        {
            deleteAndRename(RenameDelete, true);
            if (dataGridView1.Rows.Count > 0)
            {
                //Sort by Channel number
                DataView dw = ChannelTable.menu.Tables["Menu"].DefaultView;
                dw.Sort = "Chan";

                // Should we keep channel number from server
                bool KeepChanNumber = false;
                if (Properties.Settings.Default.CheckForNewDelete && Properties.Settings.Default.CheckForNewRename)
                {
                    KeepChanNumber  = true;
                }

                // Get last chan number
                int last = 0;
                if (dw.Count > 0)
                    last = (int)dw[dw.Count - 1][1];

                foreach (DataGridViewRow dgwr in dataGridView1.Rows)
                {
                    last++;

                    DataGridViewCheckBoxCell checkstate = (DataGridViewCheckBoxCell)dgwr.Cells[0];

                    if (checkstate.Value == checkstate.TrueValue)
                    {
                        //check for valid channel number
                        string chan = dgwr.Cells["Channel"].Value.ToString();
                        int test = 0;
                        bool validcast = int.TryParse(chan, out test);
                        if (validcast)
                        {
                            DataRow drOrig = ChannelTable.menu.Tables["Menu"].NewRow();
                            drOrig["Ip"] = dgwr.Cells["Ip"].Value.ToString();
                            if (KeepChanNumber)
                                drOrig["Chan"] = (int)dgwr.Cells["Channel"].Value;
                            else
                                drOrig["Chan"] = last;
                            drOrig["Name"] = dgwr.Cells["Name"].Value.ToString();
                            drOrig["Group"] = dgwr.Cells["Group"].Value.ToString();
                            drOrig["Audio"] = dgwr.Cells["Language"].Value.ToString();

                            // don't insert empty ip cells 
                            if (drOrig["Ip"].ToString() != "")
                            {
                                try
                                {
                                    ChannelTable.menu.Tables["Menu"].Rows.Add(drOrig);
                                }
                                catch { }
                            }
                        }
                    }
                }
            }
        }

        private void deleteAndRename(DataTable downloadDatatableTemp, bool doit)
        {
            if (downloadDatatableTemp != null)
            {
                int rename = 0;
                int delete = 0;
                StringBuilder sbdel = new StringBuilder();
                StringBuilder sbren = new StringBuilder();
                List<DataRow> RowsToDelete = new List<DataRow>();
                foreach (DataRow drOrig in ChannelTable.menu.Tables["Menu"].Rows)
                {
                    bool found = false;
                    foreach (DataRow drDown in downloadDatatableTemp.Rows)
                    {
                        // delete if not listed
                        string ip = drOrig["Ip"].ToString();
                        string name = drOrig["Name"].ToString();

                        if (drOrig["Ip"].ToString() == drDown["Ip"].ToString())
                        {
                            found = true;
                            // check for rename
                            if (drOrig["Name"].ToString() != drDown["Name"].ToString())
                            {
                                rename++;
                                sbren.Append(drOrig["Name"].ToString());
                                sbren.Append("->");
                                sbren.Append(drDown["Name"].ToString());
                                sbren.Append(" ");
                                if (checkBox2.CheckState == CheckState.Checked && doit)
                                {
                                    drOrig["Name"] = drDown["Name"].ToString();
                                    drOrig["Group"] = drDown["Group"].ToString();
                                    drOrig["Audio"] = drDown["Language"].ToString();
                                }
                            }
                            break;
                        }
                    }

                    if (!found)
                    {
                        delete++;
                        sbdel.Append(drOrig[1].ToString());
                        sbdel.Append(".");
                        sbdel.Append(drOrig[2].ToString());
                        sbdel.Append(" ");
                        if (checkBox1.CheckState == CheckState.Checked && doit)
                        {
                            RowsToDelete.Add(drOrig);
                        }
                    }
                }
                if (RowsToDelete != null)
                {
                    foreach (DataRow dr in RowsToDelete)
                    {
                        dr.Delete();
                    }
                }

                if ((delete > 0 || rename > 0) && !doit)
                {
                    if (delete > 0)
                    {
                        label3.Text = label3.Text + " " + delete.ToString() + " " + MLmessages.ChannelsMarkedDelete;
                    }
                    if (rename > 0)
                    {
                        label3.Text = label3.Text + " " + rename.ToString() + " " + MLmessages.ChannelsMarkedRename;
                    }
                    toolTip1.SetToolTip(label3, MLmessages.ChannelsMarkedDelete + ": " + sbdel.ToString() + Environment.NewLine + MLmessages.ChannelsMarkedRename + ": " + sbren.ToString());
                }
            }
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }
    }
}
